// 消息通知服务
// 处理系统通知、互动消息等功能

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 通知类型
const NOTIFICATION_TYPES = {
  LIKE: 'like',
  COMMENT: 'comment',
  FOLLOW: 'follow',
  SYSTEM: 'system',
  MENTION: 'mention',
  REPLY: 'reply',
  SHARE: 'share'
}

// 通知服务
export const notificationService = {
  // 获取用户通知
  async getNotifications(userId, page = 1, limit = 20, type = null) {
    try {
      await delay(300)
      
      // 模拟通知数据
      const allNotifications = this.generateMockNotifications(userId, 100)
      
      // 按类型过滤
      const filteredNotifications = type 
        ? allNotifications.filter(notification => notification.type === type)
        : allNotifications
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        notifications: filteredNotifications.slice(start, end),
        total: filteredNotifications.length,
        page,
        limit,
        totalPages: Math.ceil(filteredNotifications.length / limit),
        unreadCount: filteredNotifications.filter(n => !n.isRead).length
      }
    } catch (error) {
      console.error('获取通知失败:', error)
      throw error
    }
  },
  
  // 获取未读通知数量
  async getUnreadCount(userId) {
    try {
      await delay(100)
      
      // 模拟未读数量
      return Math.floor(Math.random() * 20)
    } catch (error) {
      console.error('获取未读通知数量失败:', error)
      return 0
    }
  },
  
  // 标记通知为已读
  async markAsRead(notificationId, userId) {
    try {
      await delay(100)
      
      // 在实际项目中，这里应该调用API更新通知状态
      // await fetch(`/api/notifications/${notificationId}/read`, {
      //   method: 'PUT',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ userId })
      // })
      
      return { success: true }
    } catch (error) {
      console.error('标记通知已读失败:', error)
      throw error
    }
  },
  
  // 标记所有通知为已读
  async markAllAsRead(userId) {
    try {
      await delay(200)
      
      // 在实际项目中，这里应该调用API更新所有通知状态
      // await fetch(`/api/notifications/read-all`, {
      //   method: 'PUT',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ userId })
      // })
      
      return { success: true }
    } catch (error) {
      console.error('标记所有通知已读失败:', error)
      throw error
    }
  },
  
  // 删除通知
  async deleteNotification(notificationId, userId) {
    try {
      await delay(100)
      
      // 在实际项目中，这里应该调用API删除通知
      // await fetch(`/api/notifications/${notificationId}`, {
      //   method: 'DELETE',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ userId })
      // })
      
      return { success: true }
    } catch (error) {
      console.error('删除通知失败:', error)
      throw error
    }
  },
  
  // 发送通知
  async sendNotification(recipientId, type, content, data = {}) {
    try {
      await delay(200)
      
      const notification = {
        id: `notification_${Date.now()}`,
        recipientId,
        type,
        content,
        data,
        isRead: false,
        createdAt: new Date().toISOString()
      }
      
      // 在实际项目中，这里应该调用API发送通知
      // const response = await fetch('/api/notifications', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(notification)
      // })
      // return await response.json()
      
      return notification
    } catch (error) {
      console.error('发送通知失败:', error)
      throw error
    }
  },
  
  // 模拟生成通知数据
  generateMockNotifications(userId, count) {
    const notifications = []
    const types = Object.values(NOTIFICATION_TYPES)
    
    for (let i = 0; i < count; i++) {
      const type = types[Math.floor(Math.random() * types.length)]
      const data = this.generateNotificationData(type)
      
      notifications.push({
        id: `notification_${i}`,
        recipientId: userId,
        type,
        content: this.getNotificationContent(type, data),
        data,
        isRead: Math.random() > 0.3, // 70%未读
        createdAt: new Date(Date.now() - i * 3600000 * Math.random() * 24).toISOString()
      })
    }
    
    // 按时间排序
    notifications.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    
    return notifications
  },
  
  // 生成通知数据
  generateNotificationData(type) {
    const videoId = `video_${Math.floor(Math.random() * 1000)}`
    const videoTitle = '热门视频标题'
    const userId = `user_${Math.floor(Math.random() * 1000)}`
    const userName = `用户${Math.floor(Math.random() * 1000)}`
    
    switch (type) {
      case NOTIFICATION_TYPES.LIKE:
        return { videoId, videoTitle, userId, userName }
      case NOTIFICATION_TYPES.COMMENT:
        return { 
          videoId, 
          videoTitle, 
          userId, 
          userName, 
          commentContent: this.getRandomComment() 
        }
      case NOTIFICATION_TYPES.FOLLOW:
        return { userId, userName }
      case NOTIFICATION_TYPES.SYSTEM:
        return { 
          title: this.getRandomSystemTitle(),
          link: '/announcement/' + Math.floor(Math.random() * 100)
        }
      case NOTIFICATION_TYPES.MENTION:
        return { 
          userId, 
          userName, 
          content: `在评论中提到了你: ${this.getRandomComment()}`
        }
      case NOTIFICATION_TYPES.REPLY:
        return { 
          videoId, 
          videoTitle, 
          userId, 
          userName, 
          replyContent: this.getRandomComment()
        }
      case NOTIFICATION_TYPES.SHARE:
        return { videoId, videoTitle, userId, userName }
      default:
        return {}
    }
  },
  
  // 获取通知内容
  getNotificationContent(type, data) {
    switch (type) {
      case NOTIFICATION_TYPES.LIKE:
        return `${data.userName} 点赞了你的视频 《${data.videoTitle}》`
      case NOTIFICATION_TYPES.COMMENT:
        return `${data.userName} 评论了你的视频 《${data.videoTitle}》: ${data.commentContent}`
      case NOTIFICATION_TYPES.FOLLOW:
        return `${data.userName} 关注了你`
      case NOTIFICATION_TYPES.SYSTEM:
        return `【系统通知】${data.title}`
      case NOTIFICATION_TYPES.MENTION:
        return data.content
      case NOTIFICATION_TYPES.REPLY:
        return `${data.userName} 回复了你的评论: ${data.replyContent}`
      case NOTIFICATION_TYPES.SHARE:
        return `${data.userName} 分享了你的视频 《${data.videoTitle}》`
      default:
        return '收到一条新通知'
    }
  },
  
  // 获取随机评论
  getRandomComment() {
    const comments = [
      '太棒了！',
      '学到了很多',
      '期待更多更新！',
      '内容很精彩',
      '支持！',
      '已收藏',
      '很实用',
      '视频质量很高',
      '感谢分享',
      '这个主题很有意思'
    ]
    return comments[Math.floor(Math.random() * comments.length)]
  },
  
  // 获取随机系统标题
  getRandomSystemTitle() {
    const titles = [
      '系统升级公告',
      '新功能上线通知',
      '活动福利大放送',
      '账号安全提醒',
      '内容推荐优化',
      '社区规范更新',
      '版权保护声明',
      '用户协议变更',
      '隐私政策调整',
      '服务条款更新'
    ]
    return titles[Math.floor(Math.random() * titles.length)]
  }
}

// 导出通知类型
export { NOTIFICATION_TYPES }

// 导出默认服务
export default notificationService